#include "Camera.h"

Camera::Camera(glm::vec3 position, float pitch, float yaw, glm::vec3 worldUp,
               float sensitiveMove, float sensitiveSpeed, float fov) {
    SensitiveMove = sensitiveMove;
    SensitiveSpeed = sensitiveSpeed;
    Pitch = pitch;
    Yaw = yaw;
    Position = position;
    WorldUp = worldUp;
    FOV = fov;
    Forward.x = glm::cos(Pitch) * glm::sin(Yaw);
    Forward.y = glm::sin(Pitch);
    Forward.z = glm::cos(Pitch) * glm::cos(Yaw);
    Right = glm::normalize(glm::cross(Forward, WorldUp));
    Up = glm::normalize(glm::cross(Forward, Right));
}

glm::mat4 Camera::GetViewMatrix() {
    return glm::lookAt(Position, Position + Forward, WorldUp);
}

void Camera::Movement(float x, float y) {
    if (isFirst) {
        lastX = x;
        lastY = y;
        isFirst = false;
    }
    float deltax, deltay;
    deltax = x - lastX;
    deltay = y - lastY;
    lastX = x;
    lastY = y;

    Pitch -= deltay * SensitiveMove;
    Yaw -= deltax * SensitiveMove;

    if (Pitch > 89.0f)
        Pitch = 89.0f;
    if (Pitch < -89.0f)
        Pitch = -89.0f;

    UpdateCameraVector();
}

void Camera::Scroll(float x, float y) {
    if (FOV >= 1.0f && FOV <= 90.0f)
        FOV += y;
    if (FOV <= 1.0f)
        FOV = 1.0f;
    if (FOV >= 90.0f)
        FOV = 90.0f;
}

void Camera::UpdateCameraPosition() {
    Position += Forward * SpeedZ * SensitiveSpeed;
    Position += Right * SpeedX * SensitiveSpeed;
    Position += Up * SpeedY * SensitiveSpeed;
}

void Camera::UpdateCameraVector() {
    Forward.x = glm::cos(Pitch) * glm::sin(Yaw);
    Forward.y = glm::sin(Pitch);
    Forward.z = glm::cos(Pitch) * glm::cos(Yaw);
    Right = glm::normalize(glm::cross(Forward, WorldUp));
    Up = glm::normalize(glm::cross(Forward, Right));
    Forward = glm::normalize(Forward);
}
